/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package windowComponents;

import com.inet.editor.BaseEditor;
import data.contact.Contact;
import data.contact.ContactFolder;
import data.email.Attachment;
import data.email.EmailAddress;
import data.email.EmailFolder;
import data.email.EmailMessage;
import enums.EmailHeaderType;
import java.awt.FlowLayout;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.Map.Entry;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.mail.Message;
import javax.mail.Message.RecipientType;
import javax.mail.internet.MailDateFormat;
import javax.swing.JTable;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author Arcanis
 */
public class EmailFolderPanel extends javax.swing.JPanel implements Observer {

    private ContactFolder contacts;
    private BaseEditor editor;

    /**
     * Creates new form EmailFolderPanel
     */
    public EmailFolderPanel(final ContactFolder contacts) {
        this.contacts = contacts;
        initComponents();
        editor = new BaseEditor(true, false, false, true);
        jPanel3.add(editor);

        jTable1.getSelectionModel().addListSelectionListener(new ListSelectionListener() {

            @Override
            public void valueChanged(ListSelectionEvent e) {
                if (!e.getValueIsAdjusting()) {
                    EmailMessage m = (EmailMessage) jTable1.getModel().getValueAt(jTable1.convertRowIndexToModel(jTable1.getSelectedRow()), 3);

                    emailsPanel.removeAll();
                    for (EmailAddress item : m.getFrom()) {
                        emailsPanel.add(new EmailLabel(contacts.getContact(item), true));
                    }
                    for (EmailAddress item : m.getTo()) {
                        emailsPanel.add(new EmailLabel(contacts.getContact(item), Message.RecipientType.TO));
                    }
                    for (EmailAddress item : m.getCc()) {
                        emailsPanel.add(new EmailLabel(contacts.getContact(item), Message.RecipientType.CC));
                    }
                    for (EmailAddress item : m.getBcc()) {
                        emailsPanel.add(new EmailLabel(contacts.getContact(item), Message.RecipientType.BCC));
                    }

                    jLabel1.setText(m.getSubject());

                    editor.setText(m.getBody(), true);


                    jPanel4.removeAll();
                    for (Attachment att : m.getAllAttachments()) {
                        jPanel4.add(new AttachmentLabel(att));
                    }

                    jPanel2.invalidate();
                    jPanel2.repaint();
                }
            }
        });
    }

    /**
     * This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        java.awt.GridBagConstraints gridBagConstraints;

        jSplitPane1 = new javax.swing.JSplitPane();
        jPanel1 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        searchTexField1 = new windowComponents.SearchTexField();
        jPanel2 = new javax.swing.JPanel();
        emailsPanel = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jPanel3 = new javax.swing.JPanel();
        jPanel4 = new javax.swing.JPanel();

        setLayout(new java.awt.GridLayout(1, 1));

        jSplitPane1.setDividerLocation(200);
        jSplitPane1.setOrientation(javax.swing.JSplitPane.VERTICAL_SPLIT);

        jPanel1.setLayout(new java.awt.GridBagLayout());

        jTable1.setAutoCreateRowSorter(true);
        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {"arcanis@email.cz", "Mongole", "12.5.2012 14:54", null},
                {"arcanis@email.cz", "Mongole", "12.5.2012 14:54", null},
                {"arcanis@email.cz", "Mongole", "12.5.2012 14:54", null},
                {"arcanis@email.cz", "Mongole", null, null}
            },
            new String [] {
                "From", "Subject", "Čas", "object"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.Object.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jTable1.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jTable1.setShowVerticalLines(false);
        jTable1.getTableHeader().setReorderingAllowed(false);
        jScrollPane1.setViewportView(jTable1);
        jTable1.getColumnModel().getColumn(3).setMinWidth(0);
        jTable1.getColumnModel().getColumn(3).setPreferredWidth(0);
        jTable1.getColumnModel().getColumn(3).setMaxWidth(0);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHEAST;
        gridBagConstraints.weightx = 1.1;
        gridBagConstraints.weighty = 1.1;
        jPanel1.add(jScrollPane1, gridBagConstraints);

        searchTexField1.setEnabled(false);
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHEAST;
        jPanel1.add(searchTexField1, gridBagConstraints);

        jSplitPane1.setLeftComponent(jPanel1);

        emailsPanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Adresy"));
        emailsPanel.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT));

        jLabel1.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);

        jPanel3.setLayout(new java.awt.GridLayout(1, 0));

        jPanel4.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT));

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(emailsPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 497, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
            .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addComponent(emailsPanel, javax.swing.GroupLayout.PREFERRED_SIZE, 62, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, 422, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        jSplitPane1.setRightComponent(jPanel2);

        add(jSplitPane1);
    }// </editor-fold>//GEN-END:initComponents
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JPanel emailsPanel;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSplitPane jSplitPane1;
    private javax.swing.JTable jTable1;
    private windowComponents.SearchTexField searchTexField1;
    // End of variables declaration//GEN-END:variables

    @Override
    public void update(Observable o, Object arg) {
        if (o instanceof EmailFolder) {
            EmailFolder folder = (EmailFolder) o;
            DefaultTableModel model = (DefaultTableModel) jTable1.getModel();

            for (int i = model.getRowCount() - 1; i >= 0; i--) {
                model.removeRow(i);
            }

            if (folder.getMessages() != null) {
                for (EmailMessage msg : folder.getMessages()) {
                    Vector<Object> v = new Vector<>();
                    v.add(msg.getFrom()[0].getAddress());
                    v.add(msg.getSubject());
                    v.add(formatDate(msg.getDate()));
                    v.add(msg);

                    model.addRow(v);
                }
            }

            jTable1.setModel(model);
        }
    }

    public static String formatDate(Date date) {
        if (date != null) {
            SimpleDateFormat form = new SimpleDateFormat("dd.MM.yyyy HH:mm");
            return form.format(date);
        }
        return "";
    }
}
